//
//  MeetUpViewController.m
//  jungoo
//
//  Created by Trung Dang Quang on 9/28/12.
//
//

#import "MeetUpViewController.h"
#import "ChatMessageViewController.h"
@interface MeetUpViewController ()

@end

@implementation MeetUpViewController

@synthesize datePickerView;
@synthesize txtPlace,txtMessage,MeetupCell01,MeetupCell03;
@synthesize peopleInfo;
@synthesize lblNote;
@synthesize startStr;

-(void)applyAppearance
{
    [self setTitle:@"Meet Up"];
    [self setLeftButtonImageActiveName:nil inactiveName:@"cancel-button" target:self action:@selector(backPressed)];
    [self setRightButtonImageActiveName:nil inactiveName:@"request_button" target:self action:@selector(requestPressed)];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]];
}

-(void) backPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void) requestPressed
{
    [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                            target:self
                             title:@"Sending..."
                          selector:@selector(delayAddConversation:)];
   
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    datePickerView.hidden = YES;
    lblNote.textColor = JGO_TEXT_COLOR_1;
    lblNote.backgroundColor = [UIColor clearColor];
    [self applyAppearance];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
-(void)dealloc
{
    [datePickerView release];
    [MeetupCell01 release];
    [MeetupCell03 release];
    [txtMessage release];
    [txtPlace release];
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - TableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 1:
            return 1;
            break;
            
        default:
            return 2;
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 1:
            return 182;
            break;
            
        default:
            return 44;
            break;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 30;
    }
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    switch (section) {
            
        case 1:
        {
            UILabel *lblText = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
            lblText.text = @"  Message:";
            lblText.backgroundColor = [UIColor clearColor];
            lblText.textColor = [UIColor colorWithRed:0. green:0.678 blue:0.941 alpha:1];
            return [lblText autorelease];
            break;
        }
        
        default:
        {
            
            break;
        }
    }
    return nil;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if (indexPath.section == 0) {
        static NSString *DateTimeCellCellIdentifier = @"MeetupCell01";
        cell = [tableView dequeueReusableCellWithIdentifier:DateTimeCellCellIdentifier];
        if (cell == nil) {
            cell  = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:DateTimeCellCellIdentifier] autorelease];
            [[NSBundle mainBundle] loadNibNamed:@"MeetupCell" owner:self options:nil];
            cell = self.MeetupCell01;
            self.MeetupCell01 = nil;
        }
    }else if (indexPath.section == 1) {
        static NSString *MeetupCell03Identifier = @"MeetupCell03";
        cell = [tableView dequeueReusableCellWithIdentifier:MeetupCell03Identifier];
        if (cell == nil) {
            cell  = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MeetupCell03Identifier] autorelease];
            [[NSBundle mainBundle] loadNibNamed:@"MeetupCell" owner:self options:nil];
            cell = self.MeetupCell03;
            self.MeetupCell03 = nil;
        }
    }
    
    
    switch (indexPath.section) {
        case 0:
        {
            UIImageView *icon = (UIImageView *)[cell viewWithTag:1];
            
            UILabel *firstText = (UILabel *)[cell viewWithTag:2];
            UILabel *secondText = (UILabel *)[cell viewWithTag:3];
            firstText.textColor = [UIColor colorWithRed:0. green:0.678 blue:0.941 alpha:1];
            secondText.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
            switch (indexPath.row) {
                case 0:
                {
                    icon.image = [UIImage imageNamed:@"s-time-icon.png"];
                    firstText.text = @"Suggest Time:";
                    secondText.text = startStr;
                    
                    
                    break;
                }
                case 1:
                {
                    icon.image = [UIImage imageNamed:@"place-icon.png"];
                    firstText.text = @"Suggest Place:";
                    secondText.hidden = YES;
                    self.txtPlace = [[UITextField alloc]initWithFrame:secondText.frame];
                    self.txtPlace.delegate = self;
                    [cell addSubview:self.txtPlace];
                    txtPlace.backgroundColor = [UIColor clearColor];
                    
                    break;
                }
                default:
                {
                    break;
                }
            }
            break;
        }
        case 1:
        {
            self.txtMessage = (UITextView *)[cell viewWithTag:2];
            self.txtMessage.backgroundColor = [UIColor clearColor];
            cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
            break;
        }
        default:
            break;
    }
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        datePickerView.datePickerMode = UIDatePickerModeTime;
        datePickerView.hidden = NO;
        lblNote.hidden = YES;
        [self.txtPlace resignFirstResponder];
        [self.txtMessage resignFirstResponder];
    }else
    {
        datePickerView.hidden = YES;
        lblNote.hidden = NO;
    }
    
}

#pragma mark -
#pragma mark UIPickerViewDelegate

-(IBAction) timeChange: (id)sender
{
        NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
        [outputFormatter setDateFormat:@"h:mm a"];
        
        self.startStr = [outputFormatter stringFromDate:self.datePickerView.date];
        
        [outputFormatter release];
        
    
        [self.tableView reloadData];
	
}
/*
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	[txtPlace resignFirstResponder];
    datePickerView.hidden = YES;
    lblNote.hidden = NO;
	[super touchesBegan:touches withEvent:event];
}
*/
#pragma mark - TextField Delegete && TextView Delegete

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 218, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionNone
                                  animated:YES];
    return YES;
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                          atScrollPosition:UITableViewScrollPositionNone
                                  animated:YES];
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    UITableViewCell *cell = (id)textView.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 130, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionNone
                                  animated:YES];
    
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

- (void)delayAddConversation:(MBProgressHUD*)progress
{
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSError *error = nil;
    NSString *inviteeIds = [peopleInfo objectForKey:@"user_id"];
    NSString *textMessage = @"Meet up request";
    NSString *content = [NSString stringWithFormat:@"Meet up request \n Suggest time: %@ \n Suggest place: %@ \n Message: %@",self.startStr,txtPlace.text,txtMessage.text];
    NSDictionary *conver = [JGoAPI createConversationWithUserId:userId
                        conversationName:textMessage
                              inviteeIds:inviteeIds
                                   error:&error];
    if (!error) {
        NSString *conversionId = [[conver objectForKey:@"data"] objectForKey:@"id"];
     
        BOOL result = [JGoAPI addMessageWithUserId:userId
                                    conversationId:conversionId
                                              type:@"0"
                                           content:content
                                             error:&error];
        
        if (result) {
           
            ChatMessageViewController *cmVC = [[[ChatMessageViewController alloc] initWithNibName:@"ChatMessageViewController"
            bundle:nil] autorelease];
            cmVC.conversionId = conversionId;
            
            [self.navigationController pushViewController:cmVC animated:YES];
            
        }
        else {
            [JGoUtility showAlert:[error localizedDescription]];
        }
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
}


@end
